package cn.wowjoy.office.materialinspection.applyfor.produce;

import android.app.Activity;
import android.arch.lifecycle.MediatorLiveData;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.common.adapter.StockApplyLrAdapter;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.request.GoodStockRequest;
import cn.wowjoy.office.data.response.ApplyDemandHeadDetailItem;
import cn.wowjoy.office.data.response.StockStorageResponse;
import cn.wowjoy.office.utils.ToastUtil;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2018/4/18.
 */

public class StockApplyProduceViewModel extends NewBaseViewModel {
    @Inject
    ApiService apiService;


    public List<ApplyDemandHeadDetailItem> mApplyDemandHeadDetailItems;



    public StockApplyLrAdapter mOtherOutLrAdapter = new StockApplyLrAdapter();
    public LRecyclerViewAdapter adapter = new LRecyclerViewAdapter(mOtherOutLrAdapter);
    @Inject
    public StockApplyProduceViewModel(@NonNull NewMainApplication application) {
        super(application);
        mOtherOutLrAdapter.setmItemEventHandler(this);
    }

    @Override
    public void onCreateViewModel() {

    }
    private MediatorLiveData<ApplyDemandHeadDetailItem> jump = new MediatorLiveData<>();
    public MediatorLiveData<ApplyDemandHeadDetailItem> getJump() {
        return jump;
    }
    public void jump(ApplyDemandHeadDetailItem model) {
        jump.setValue(model);
    }

    private void smoothMoveToPosition(int position, LinearLayoutManager layoutManager, RecyclerView rv) {
        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        if (position <= firstItem) {
            rv.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            int top = rv.getChildAt(position - firstItem).getTop();
            rv.smoothScrollBy(0, top);
        } else {
            rv.smoothScrollToPosition(position);
            // move = true;
        }

    }

    public GoodStockRequest addDVO(ApplyDemandHeadDetailItem model) {
        GoodStockRequest g = new GoodStockRequest();
        g.setGoodsCode(model.getGoodsCode());
        g.setInStorageDetailBatchNumber(model.getInStorageDetailBatchNumber());
        g.setInStorageDetailEffecticeDate(model.getInStorageDetailEffectiveDate());
        g.setQrCode(model.getQrCode());
        g.setInStorageDetailPrice(model.getInStorageDetailPrice());

        g.setEffectiveDate(model.getEffectiveDate());
        g.setPrice(model.getPrice());
        g.setBatchNumber(model.getBatchNumber());
        return g;
    }

    /**
     * 要保存扫到的正确货物  无论是手工的还是扫码的
     * 页面上显示   List要新加
     *
     * @param model
     */
    public void updateFactOut(ApplyDemandHeadDetailItem model, Activity activity, LinearLayoutManager layoutManager, RecyclerView rv) {
        /** 1.扫到同一种物品  改变数量
         判断当前的可出库数量 和 现有的数量做比较
         a.库存不足  提示
         b.库存充足  数量+1  页面更新
         2.手动添加同一种物品
         a.通过 编辑添加的

         b.通过 搜索添加的
         *
         */

        int sum = 0;
        boolean isOver = false;
        for (ApplyDemandHeadDetailItem s : mApplyDemandHeadDetailItems) {
            sum++;
            if (!TextUtils.isEmpty(s.getGoodsCode()) && !TextUtils.isEmpty(model.getGoodsCode())) {
                Log.e("PXY", "ApplyDemandHeadDetailItem:" + s.toString());
                Log.e("PXY", "model:" + model.toString());
                if (s.getGoodsCode().equals(model.getGoodsCode())) {
                    if (model.isScan() && s.isScan()) {
                        if (s.isFull(model)) {
                            if(s.isFullT(model)){ // 为出库数量的 判断
                                s.setNeedNumber(s.getNeedNumber() + 1);
                                //页面更新
                                int position = update(s);
                                smoothMoveToPosition(position, layoutManager, rv);
                                mOtherOutLrAdapter.changeItem(s);
                                s.addqRVOList(addDVO(model));
                                isOver = true;
                                break;
                            }else{
                                ToastUtil.toastWarning(activity, "添加失败,已超过本笔申请单未出库数量", -1);
                                isOver = true;
                                break;
                            }

                        } else {
                            //提示 库存不足
                            ToastUtil.toastWarning(activity, "添加失败,已超过本笔申请单最大数量", -1);
                            isOver = true;
                            break;
                        }
                    }
                }
            }
        }
        if (sum == mApplyDemandHeadDetailItems.size() && !isOver) {
//            if(model.isHand()){
//
//            }
            ToastUtil.toastWarning(activity, "该物资不在本明细单内，请核对后扫码", -1);
        }
    }
    MediatorLiveData<LiveDataWrapper<ApplyDemandHeadDetailItem>>  pdaSubmit = new MediatorLiveData<>();
    public void submit( Activity activity) {
        pdaSubmit.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.submitOutStorageByDemandNew(mApplyDemandHeadDetailItems)
                .flatMap(new ResultDataParse<ApplyDemandHeadDetailItem>())
                .compose(new RxSchedulerTransformer<ApplyDemandHeadDetailItem>())
                .subscribe(new Consumer<ApplyDemandHeadDetailItem>() {
                               @Override
                               public void accept(ApplyDemandHeadDetailItem resultEmpty) throws Exception {
                                   pdaSubmit.setValue(LiveDataWrapper.success(resultEmpty));
                                   ToastUtil.toastImage(getApplication().getApplicationContext(), "提交成功", -1);

                                   activity.setResult(Constants.RESULT_OK);
                                   activity.finish();
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                pdaSubmit.setValue(LiveDataWrapper.error(throwable, null));

                       //         ToastUtil.toastImage(getApplication().getApplicationContext(), throwable.getMessage(), -1);
                            }
                        });
        addDisposable(disposable);
    }
    private MediatorLiveData<LiveDataWrapper<StockStorageResponse>> permission = new MediatorLiveData<>();

    public MediatorLiveData<LiveDataWrapper<StockStorageResponse>> getPermission() {
        return permission;
    }
    public void applyPermission() {
        permission.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.isExamineAndConfirmOut()
                .flatMap(new ResultDataParse<StockStorageResponse>())
                .compose(new RxSchedulerTransformer<StockStorageResponse>())
                .subscribe(new Consumer<StockStorageResponse>() {
                    @Override
                    public void accept(StockStorageResponse taskListResponse) throws Exception {
                        //获取的数据发送给Activity来使用
                        permission.setValue(LiveDataWrapper.success(taskListResponse));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        permission.setValue(LiveDataWrapper.error(throwable, null));
                    }
                });
        addDisposable(disposable);
    }
    public int update(ApplyDemandHeadDetailItem s) {
        int position = mApplyDemandHeadDetailItems.indexOf(s);
        mApplyDemandHeadDetailItems.remove(position);
        mApplyDemandHeadDetailItems.add(position, s);
        return position;
    }

    MediatorLiveData<ApplyDemandHeadDetailItem> edit = new MediatorLiveData<>();

    public void editItemStock(ApplyDemandHeadDetailItem recordResponse, int position) {
        recordResponse.setNotifyPosition(position);
        edit.setValue(recordResponse);
//        totalMoney();
    }

    MediatorLiveData<ApplyDemandHeadDetailItem> delete = new MediatorLiveData<>();

    public void delete(ApplyDemandHeadDetailItem recordResponse, int position) {
        recordResponse.setDeletePosition(position);
        delete.setValue(recordResponse);
//        totalMoney();
    }


    private MediatorLiveData<LiveDataWrapper<ApplyDemandHeadDetailItem>> scanData = new MediatorLiveData<>();
    public MediatorLiveData<LiveDataWrapper<ApplyDemandHeadDetailItem>> getScanData() {
        return scanData;
    }
    public void queryByScan(String qcCode) {
        scanData.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getQRByQRCodePdaApply(qcCode)
                .flatMap(new ResultDataParse<ApplyDemandHeadDetailItem>())
                .compose(new RxSchedulerTransformer<ApplyDemandHeadDetailItem>())
                .subscribe(new Consumer<ApplyDemandHeadDetailItem>() {
                    @Override
                    public void accept(ApplyDemandHeadDetailItem taskListResponse) throws Exception {
                        //获取的数据发送给Activity来使用
                        scanData.setValue(LiveDataWrapper.success(taskListResponse));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        scanData.setValue(LiveDataWrapper.error(throwable, null));
                    }
                });
        addDisposable(disposable);
    }

}
